package com.stars.easyms.datasource.loadbalancer;

import com.stars.easyms.datasource.EasyMsDataSource;
import com.stars.easyms.datasource.EasyMsDataSourceSet;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>className: RoundRobinDataSourceLoadBalancer</p>
 * <p>description: 轮询模式数据源负载均衡器：轮询模式：依次选择数据库进行操作</p>
 *
 * @author guoguifang
 * @version 1.2.1
 * @date 2019-05-13 13:52
 */
final class RoundRobinDataSourceLoadBalancer implements DataSourceLoadBalancer {

    private final Map<EasyMsDataSourceSet, AtomicInteger> roundRobinIndexMap = new ConcurrentHashMap<>(32);

    @Override
    public EasyMsDataSource getDataSource(EasyMsDataSourceSet easyMsDataSourceSet) {
        AtomicInteger roundRobinIndex = roundRobinIndexMap.computeIfAbsent(easyMsDataSourceSet, key -> new AtomicInteger(0));
        return easyMsDataSourceSet.get(Math.abs(roundRobinIndex.getAndAdd(1) % easyMsDataSourceSet.size()));
    }
}